<template>
  <div id="addCompetitionView">
    <h2>创建比赛</h2>
    <a-form :model="form" label-align="left">
      <a-form-item field="name" label="比赛名称">
        <a-input v-model="form.name" placeholder="请输入标题" />
      </a-form-item>
      <a-form-item label="比赛时间">
        <a-range-picker
        v-model="rangeTime"
        style="width: 360px"
        show-time
        :time-picker-props="{ defaultValue: ['00:00:00', '09:09:06'] }"
        @change="onChange"
        format="YYYY-MM-DD HH:mm"
        />
      </a-form-item>
      <a-form-item field="description" label="比赛公告">
        <a-textarea v-model="form.description" allow-clear/>
      </a-form-item>
      <a-form-item field="questionList" label="题目列表">
        <a-table :columns="columns" :data="questionList" row-key="id" v-model:selectedKeys="form.questionList" :row-selection="rowSelection">
          <template #tagsText="{ record }">
            <a-space wrap>
              <a-tag v-for="(tag, index) of record.tagsText" :key="index" color="green">{{ tag }}
              </a-tag>
            </a-space>
          </template>
          <template #difficultyText = "{record}">
            <a-tag style="font-weight: bolder" :style="{color: getColor(record.difficulty)}" size="large">{{ record.difficultyText }}</a-tag>
          </template>
        </a-table>
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" style="min-width: 200px" @click="doSubmit">提交
          </a-button>
          <a-button type="primary" style="min-width: 200px" @click="toBackView">返回
          </a-button>
        </a-space>
        
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, onMounted, ref, reactive } from "vue";
import MdEditor from "@/components/MdEditor.vue";
import { QuestionControllerService, CommonControllerService } from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRoute, useRouter } from "vue-router";
import { CompetitionControllerService } from "../../../generated";

const route = useRoute();
// 如果页面地址包含 update，视为更新页面
const updatePage = route.path.includes("update");

const router = useRouter();

let form = ref({
  id: undefined,
  name: "",
  startTime: "",
  endTime: "",
  description: "",
  questionList: [],
});

let rangeTime = ref([])
let questionList = ref([])
const rowSelection = reactive({
      type: 'checkbox',
      showCheckedAll: true,
      onlyCurrent: false,
    });
const columns = [
  {
    title: "题目名称",
    dataIndex: "title",
    width: 240,
  },
  {
    title: "标签",
    slotName: "tagsText",
    width: 240,
  },
  {
    title: "难度",
    slotName: "difficultyText",
    width: 120,
  },
];

interface Props {
  id: string;
}

const props = withDefaults(defineProps<Props>(), {
  id: "",
});

/**
 * 根据题目 id 获取老的数据
 */
const loadData = async () => {
  const res = await QuestionControllerService.listPageCompetitionQuestionVoUsingPost(
    props.id as any
  );
  if (res.code === 0) {
    questionList.value = res.data.records as any;
  } else {
    message.error("加载失败，" + res.message);
  }
  if(updatePage){
    form.value.id = props.id
    // 获取竞赛的题目列表
    const res2 = await CompetitionControllerService.getCompetitionByIdUsingGet(
      props.id as any
    )
    form.value.name = res2.data?.name
    form.value.startTime = res2.data?.startDateTime
    rangeTime.value[0] = res2.data?.startDateTime
    form.value.endTime = res2.data?.endDateTime
    rangeTime.value[1] = res2.data?.endDateTime
    form.value.description = res2.data?.description
    form.value.questionList = res2.data?.questionList
  }
  
};

onMounted(() => {
  // if (sessionStorage.getItem('name')) {
  //   form.value.name = sessionStorage.getItem('name')
  //   // 数据拿取之后，清除缓存
  //   sessionStorage.removeItem('name');
  // }
  // if (sessionStorage.getItem('startTime')) {
  //   form.value.startTime = sessionStorage.getItem('startTime')
  //   rangeTime.value[0] = new Date(form.value.startTime)
  //   // 数据拿取之后，清除缓存
  //   sessionStorage.removeItem('startTime');
  // }
  // if (sessionStorage.getItem('endTime')) {
  //   form.value.endTime = sessionStorage.getItem('endTime')
  //   rangeTime.value[1] = new Date(form.value.endTime)
  //   // 数据拿取之后，清除缓存
  //   sessionStorage.removeItem('endTime');
  // }
  // if (sessionStorage.getItem('description')) {
  //   form.value.description = sessionStorage.getItem('description')
  //   // 数据拿取之后，清除缓存
  //   sessionStorage.removeItem('description');
  // }
  // if (sessionStorage.getItem('questionList')) {
  //   questionList.value = JSON.parse(sessionStorage.getItem('questionList'))
  //   console.log("questionList",JSON.parse(sessionStorage.getItem('questionList')));
  //   // 数据拿取之后，清除缓存
  //   sessionStorage.removeItem('questionList');
  // }
  loadData();
});

const doSubmit = async () => {
  const res = await CompetitionControllerService.saveCompetitionUsingPost(
    form.value
  );
  if (res.code === 0) {
    message.success("操作成功");
  } else {
    message.error("操作失败，" + res.message);
  }
  toHomeView();
};

const getColor = (status:number) => {
  switch(status){
    case 1:
      return "green";
    case 2:
      return "blue";
    case 3:
      return "red";
  }
}

const onChange = (dateString: any, datea: any) => {
  if(dateString){
    form.value.startTime = dateString[0];
    form.value.endTime = dateString[1];
  }else{
    form.value.startTime = "";
    form.value.endTime = "";
  }
}

const toHomeView = () => {
  router.push({
    path: `/competition`,
  });
};

const toBackView = () => {
  router.back();
}

</script>

<style scoped>
#addCompetitionView {}
</style>
